package com.ys.service.purchase.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.TypeReference;
import com.ys.entity.business.TpProductBasisComponent;
import com.ys.entity.purchase.*;
import com.ys.enume.purchase.TcgOfflinePurchaseInStorageEnum;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.mapper.business.TpProductActiveComponentMapper;
import com.ys.mapper.business.TpProductActiveMapper;
import com.ys.mapper.business.TpProductBasisComponentMapper;
import com.ys.mapper.purchase.TcgPurchaseByOrderMapper;
import com.ys.mapper.purchase.TcgPurchaseByOrderSonMapper;
import com.ys.service.purchase.TcgOfflinePurchaseInStorageService;
import com.ys.service.purchase.TcgPurchaseByOrderService;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bo.util.HttpUtil;
import com.ys.cache.CacheUtils;
import com.ys.config.MyConfig;
import com.ys.constant.AppConstant;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.mapper.purchase.PurchaseMapper;
import com.ys.mapper.purchase.TsApi1688ToKenMapper;
import com.ys.service.log.ApiLogService;
import com.ys.service.purchase.Api1688Service;
import com.ys.util.ApiHttpUtils;
import com.ys.util.DateUtil;
import com.ys.util.alibaba.ApiHmacSHA1Utils;
import com.ys.util.dhecp.StringUtils;
import com.ys.util.dhecp.TypeUtils;
import com.ys.vo.R;

@Service("api1688Service")
public class Api1688ServiceImpl implements Api1688Service {

	private static final Logger logger = Logger.getLogger(Api1688ServiceImpl.class);


	//1688系统名称
	private static final String OPEN1688_SYSTEM_NAME = "1688";

	@Autowired
	private ApiLogService apiLogService;



	@Autowired
	private TsApi1688ToKenMapper tsApi1688ToKenMapper;

	@Autowired
	private PurchaseMapper purchaseMapper;

	@Autowired
	private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

	@Autowired
	private TcgPurchaseByOrderSonMapper tcgPurchaseByOrderSonMapper;

	@Autowired
	private TcgPurchaseByOrderService tcgPurchaseByOrderService;

	@Autowired
    private TpProductActiveMapper tpProductActiveMapper;

	@Autowired
	private TpProductActiveComponentMapper tpProductActiveComponentMapper;

	@Autowired
	private TpProductBasisComponentMapper tpProductBasisComponentMapper;

	@Autowired
	private TcgOfflinePurchaseInStorageService tcgOfflinePurchaseInStorageService;

	@Override
	@Transactional
	public R viewOrderBeforeCreate(String orderNo) {

		Map<String, String> postParams = new HashMap<String, String>();
		String token = getAccessToken();
		long aop_timestamp = new Date().getTime();
		postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
		postParams.put("access_token", token);
		postParams.put("flow", "general");//流程
		postParams.put("tradeType", "fxassure");// 交易类型
		
		TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
		TcgPurchaseByPlan tcgPurchasePlan = new TcgPurchaseByPlan().setBid(tcgPurchaseOrder.getBid()).queryFirst();
		TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setStatus(1).setId(tcgPurchaseOrder.getPurchaseAddressId()).queryFirst();
		ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(tcgPurchasePlan.getVgsbm()).queryFirst();

		List<TcgPurchaseByOrderSon> orderItemList = new TcgPurchaseByOrderSon().setPid(tcgPurchaseOrder.getId()).queryList();

		List<Map<String, Object>> cargoParamList = new ArrayList<Map<String, Object>>(); // 商品信息
		Map<String, Object> cargoParamItem = null;
		if (orderItemList != null && orderItemList.size() > 0) {
			for (TcgPurchaseByOrderSon orderItem : orderItemList) {
				TcgPurchaseByPlanSon tcgPurchasePlanSon = new TcgPurchaseByPlanSon().setId(orderItem.getPurchasePlanSonId()).queryFirst();
				cargoParamItem = new HashMap<>();
				
				String spectId = orderItem.getSpecId();
				if (spectId != null && spectId.length() > 0) {
					cargoParamItem.put("specId", orderItem.getSpecId());
				}
				cargoParamItem.put("quantity", tcgPurchasePlanSon.getSubTotalAmount());
				cargoParamItem.put("offerId", orderItem.getGoodsId());
				cargoParamList.add(cargoParamItem);
			}
		}
		
        Map<String, Object> addressParam = new HashMap<>();
        addressParam.put("fullName", thrOperateCompanyApply.getVgsjc());
        addressParam.put("mobile", tcgPurchaseAddress.getVFhrSj());
        addressParam.put("phone", tcgPurchaseAddress.getPhone());
        addressParam.put("postCode", tcgPurchaseAddress.getVYbH());
        addressParam.put("provinceText", tcgPurchaseAddress.getVSfH());
        addressParam.put("cityText", tcgPurchaseAddress.getVDsH());
        addressParam.put("areaText", tcgPurchaseAddress.getVCqH());
        addressParam.put("townText", "");
        addressParam.put("address", thrOperateCompanyApply.getVGsDz());
		
		postParams.put("cargoParamList", JSON.toJSONString(cargoParamList));
		//收货地址
		if (addressParam != null) {
			//取收货人地址，加上扩展信息
			String shAddress = addressParam.containsKey("address") ? addressParam.get("address").toString() : "";
			if (shAddress != null && shAddress.length() > 0) {
				addressParam.put("address", shAddress);
			}
			postParams.put("addressParam", JSON.toJSONString(addressParam));
		}
		
		//发票信息
        Map<String, Object> invoiceParam = null;
        //当发票设置类型不为-1时，创建发票信息
        if (!tcgPurchaseAddress.getInvoiceType().equals("-1")) {
            invoiceParam = new HashMap<>();
            invoiceParam.put("invoiceType", tcgPurchaseAddress.getInvoiceType());
            invoiceParam.put("fullName", tcgPurchaseAddress.getVSpr());
            invoiceParam.put("mobile", tcgPurchaseAddress.getVSprSj());
            invoiceParam.put("phone", tcgPurchaseAddress.getVSprDh());
            invoiceParam.put("postCode", tcgPurchaseAddress.getVYbP());
            invoiceParam.put("provinceText", tcgPurchaseAddress.getVSfP());
            invoiceParam.put("cityText", tcgPurchaseAddress.getVDsP());
            invoiceParam.put("areaText", tcgPurchaseAddress.getVCqP());
            invoiceParam.put("townText", "");
            invoiceParam.put("address", tcgPurchaseAddress.getVDzP());
            invoiceParam.put("companyName", thrOperateCompanyApply.getVgsmc());
            invoiceParam.put("taxpayerIdentifier", tcgPurchaseAddress.getVTax());
            if (tcgPurchaseAddress.getInvoiceType().equals("1")) {
            	String bankAndAccount = (tcgPurchaseAddress.getVBank() != null && tcgPurchaseAddress.getVBank().length() > 0 ? tcgPurchaseAddress.getVBank() : "")
            			+ (tcgPurchaseAddress.getVAccount() != null && tcgPurchaseAddress.getVAccount().length() > 0 ? tcgPurchaseAddress.getVAccount() : "");
                invoiceParam.put("bankAndAccount", bankAndAccount);
                invoiceParam.put("localInvoiceId", "");
            }
			postParams.put("invoiceParam", JSON.toJSONString(invoiceParam));
        }
		
		String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.createOrder.preview/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
		postParams.put("_aop_signature", aop_signature);
		
		String url = AppConstant.VIEW_BEFORE_CREATE_ORDER_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
		String result = HttpUtil.sendPost(url, postParams, "utf8");
		// result格式：错误/成功
		//{"errorCode":"500_001","errorMsg":"商品[600537861754]不支持在线交易，无法下单。","success":false}
		//{"orderPreviewResuslt":[{"tradeModeNameList":["fxassure","creditBuy","bank"],"status":true,"taoSampleSinglePromotion":false,"sumPayment":61727,"sumCarriage":5440,"sumPaymentNoCarriage":56287,"flowFlag":"general","cargoList":[{"amount":564.0,"finalUnitPrice":6.0,"specId":"a874629c1e91f3456c614d5c5987221f","skuId":4860380581758,"offerId":643057795431,"cargoPromotionList":[{"promotionId":"plus-1074240391-817286931784|AliB2Bdszk-62563302575_817286931784","selected":false,"text":"省36:PLUS会员价","desc":"<ul><li>PLUS会员价：省36.00元</li></ul>","freePostage":false,"discountFee":3600}]}],"shopPromotionList":[{"promotionId":"AliB2BSellerFreePostage-71923392030_1088974719496","selected":true,"text":"省1.13:满优惠","desc":"<ul><li>满优惠：省1.13元</li></ul>","freePostage":false,"discountFee":113}],"tradeModelList":[{"name":"担保交易","description":"2023年08月10日00:00:00至2023年09月06日23:59:59买家下单后，请在2023年09月07日00时30分前使用1688网站提供的多种支付方式完成付款，超时未支付则系统自动关闭交易订单；付款成功后卖家发货，买家在10天内确认收货。注：买家可使用1688网站提供的多种支付方式完成付款。特别提醒：如卖家已开通极速到账服务，将优先适用极速到账交易，买家支付款项将直接打入卖家账户，详见《极速到账交易及争议处理规则》","tradeType":"fxassure","opSupport":true},{"name":"先采后付（免费赊账）","description":"2023年08月10日00:00:00至2023年09月06日23:59:59买家下单后，请在2023年09月07日00时30分前支付，超过未支付则关闭交易订单；付款成功后卖家发货，买家在10天内确认收货，并在账期（或付款日）到期时付款。您可享受先下单、后还款的金融权益，下单后根据支付渠道提示的到期还款日进行还款。注：L4以上诚e赊用户可专享最长98天免费账期特权，具体以实际显示为准。贷款支付分期还款，可享立减支付优惠，具体优惠以实际支付金额为准，L5-L6额外尊享30天免息权益，具体活动以收银台显示为准。","tradeType":"creditBuy","opSupport":true},{"name":"银行转账","description":" 买家下单后需在5天内完成付款（逾期未付款交易将关闭），付款成功后卖家发货，买家在10天内确认收货后款项进入卖家账户（逾期将自动确认收货）。 可享立减优惠以收银台实际支付金额为准。 ","tradeType":"bank","opSupport":true}]}],"success":true,"unsupportedCrossBorderPayOfferList":[]}
		//
		JSONObject resultJO = JSON.parseObject(result);
		if (resultJO.containsKey("success") && resultJO.getBoolean("success") == false) {
			return R.error(resultJO.getString("errorMsg"));
		}
		JSONArray orderPreviewResusltJA = resultJO.getJSONArray("orderPreviewResuslt");
		JSONObject orderPreviewResusltJO = orderPreviewResusltJA.getJSONObject(0);
		JSONArray shopPromotionListJA = orderPreviewResusltJO.getJSONArray("shopPromotionList");
		List<ViewOrderBeforeCreateDto.RowDto> rows = new ArrayList<ViewOrderBeforeCreateDto.RowDto>();
		for (int i = 0; shopPromotionListJA != null && i < shopPromotionListJA.size(); i++) {
			JSONObject shopPromotionListJO = shopPromotionListJA.getJSONObject(i);
			
			String promotionId = shopPromotionListJO.getString("promotionId");
			boolean selected = shopPromotionListJO.getBoolean("selected");
			String text = shopPromotionListJO.getString("text");
			BigDecimal discountFee = shopPromotionListJO.getBigDecimal("discountFee");
			rows.add(new ViewOrderBeforeCreateDto.RowDto(promotionId, selected, text, discountFee));
		}
		
		ViewOrderBeforeCreateDto dto = new ViewOrderBeforeCreateDto(rows);

		return R.ok(dto);

	}

	@Override
	public String getAccessToken() {
		TsApi1688ToKen tsApi1688ToKen = new TsApi1688ToKen().queryFirst();
		
		Date now = new Date();
		String yyyyMMddhhmmss = DateUtil.getYYYY_MM_DD_HH_mm_ss(now).replace("-", "").replace(" ", "").replace(":", "");
		if (tsApi1688ToKen.getRefreshTokenTimeout().compareTo(yyyyMMddhhmmss) > 0) {
			return tsApi1688ToKen.getAccessToken();
		}
		
		String redirectUrl = AppConstant.REFRESH_TOKEN_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey()).replace("YOUR_APPSECRET", MyConfig.get1688AppSecret()).replace("REFRESH_TOKEN", tsApi1688ToKen.getRefreshToken());
		String result = HttpUtil.sendGet(redirectUrl);
		/* result格式：
		{"access_token":"352591e0-0677-44a4-a66b-73e6241fc5ca","aliId":"2209498529735","resource_owner":"ease逸思电商","expires_in":"-1884277804","memberId":"b2b-220949852973588bb4"}
		 */
		logger.info("通过refresh_token值获取新的token结果为---" + result);
		if (result != null && result.length() > 0) {
			JSONObject resultJO = JSON.parseObject(result);

			String accessToken = resultJO.getString("access_token");
			tsApi1688ToKen.setAccessToken(accessToken);
			tsApi1688ToKen.setRefreshTokenTimeout(resultJO.getString("refresh_token_timeout"));
			tsApi1688ToKenMapper.update(tsApi1688ToKen);
			return accessToken;
		}
		return null;
	}

	@Override
	@Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
	public R get1688ProductDetail(String code) {
		String type = "Get1688ProductList";
		try {
			//查询listing主表和子件参数参数
			TpProductActive tpProductActive = new TpProductActive().setCode(code).queryFirst();
			if (tpProductActive == null){
				return R.error("listing数据不存在,核实后再操作!");
			}
			List<TpProductActiveComponent> tpProductActiveComponent = new TpProductActiveComponent().setPcode(code).queryList();
			if (tpProductActiveComponent.size() == 0){
				return R.error("listing子件数据至少需要一条,核实后再操作!");
			}

			//20230301日改成根据1688商品ID与系统商品ID为主键删除相应数据
			Map<String, Object> deleteMap = new HashMap<>();
			//20240806日修改只根据系统商品编码全部删除
//						deleteMap.put("goodsID", productID);
			deleteMap.put("pCode", tpProductActive.getCode());
			purchaseMapper.deleteDistributionByMap(deleteMap);
			//错误的铺货标识
			List<String> errorNoList = new ArrayList<>();
			for (TpProductActiveComponent tpProductActiveComponent1 : tpProductActiveComponent){
				Long productId = TypeUtils.getSafeLong(tpProductActiveComponent1.getLinkInMark(), 0L);
				if (productId > 0) {
					boolean result = get1688ProductDetailByApi(productId,tpProductActive, type);
					if (result == false) {
						errorNoList.add(tpProductActiveComponent1.getLinkInMark());
					}
				}else {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("listing子件数据铺货标识不允许为0,核实后再操作!");
				}
			}
			String message = "获取1688商品信息成功！";
			if (errorNoList.size() > 0) {
				message = message + "，其中失败的商品编号为[" + String.join(",", errorNoList) + "]";
				apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "code：" + code, JSON.toJSONString(message), 500, message);
				return R.error(message);
			}
		}catch (Exception ex) {
			logger.error("调用获取1688商品信息接口出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "code：" + code, JSON.toJSONString(ex.getMessage()), 500, ex.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error(ex.getMessage());
		}
		return R.ok("铺货成功!");
	}



	/**
	 * 获取单个商品信息
	 *
	 * @param productId 铺货标识
	 * @param tpProductActive Lisiting主表信息
	 * @param type 类型
	 * @return
	 */
	private boolean get1688ProductDetailByApi(Long productId, TpProductActive tpProductActive, String type) {
		boolean prodResult = false;
		if (productId <= 0) {
			return prodResult;
		}
		long aop_timestamp = new Date().getTime();
		String token = getCacheAccessToken();

		//铺货POST参数
		Map<String, String> pushPostParams = null;
		pushPostParams = new HashMap<>();
		long[] productIdList = new long[1];
		productIdList[0] = productId;
		pushPostParams.put("productIdList", JSON.toJSONString(productIdList));
		pushPostParams.put("access_token", token);
		pushPostParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
		String push_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.product.push/alibaba.cross.syncProductListPushed/" + MyConfig.get1688AppKey(), pushPostParams, MyConfig.get1688AppSecret());
		pushPostParams.put("_aop_signature", push_signature);
		//获取产品信息参数
		Map<String, String> postParams = null;
		postParams = new HashMap<>();
		postParams.put("productId", String.valueOf(productId));
		postParams.put("access_token", token);
		postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
		String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.product/alibaba.cross.productInfo/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
		postParams.put("_aop_signature", aop_signature);

		try {
			if (StringUtils.isEmpty(token)){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "调用1688将商品加入铺货列表-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				return prodResult;
			}
			String pushUrl = AppConstant.PUSH_PRODUCINFOURL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
			JSONObject pushJsonObject = ApiHttpUtils.sendHttpClientPost(pushUrl, pushPostParams);
			if (pushJsonObject == null) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "调用1688将商品加入铺货列表-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), JSON.toJSONString(pushJsonObject), 400, "调用1688将商品加入铺货列表接口出错，结果返回传JSON对象出错！");
				return prodResult;
			}
			JSONObject pushResultItemObject = pushJsonObject.getJSONObject("result");
			if (pushResultItemObject != null) {
				boolean pushSuccess = false;
				if (pushResultItemObject.containsKey("success")) {
					pushSuccess = pushResultItemObject.getBoolean("success");
				}
				if (pushSuccess == true) {
					String url = AppConstant.GET_PRODUCINFOURL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
					JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
					if (jsonObject == null) {
						apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 400, "调用1688获取产品信息接口出错，结果返回传JSON对象出错！");
						return prodResult;
					}
					boolean success = false;
					if (jsonObject.containsKey("success")) {
						success = jsonObject.getBoolean("success");
					}
					if (success == false) {
						String errorMsg = "";
						if (jsonObject.containsKey("message")) {
							errorMsg = jsonObject.getString("message");
						}
						if (jsonObject.containsKey("error_message")) {
							errorMsg = jsonObject.getString("error_message");
						}
						apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 400, "调用1688获取产品信息接口出错，具体错误为:" + errorMsg);
						return prodResult;
					}
					List<TcgDistribution> insertDataList = new ArrayList<>();
					TcgDistribution distribution = null;
					JSONObject productInfoObj = jsonObject.getJSONObject("productInfo");
					if (productInfoObj != null) {
						String productID = productInfoObj.get("productID").toString();
						String status = (String) productInfoObj.get("status");
						String subject = (String) productInfoObj.get("subject");
						String supplierUserId = (String) productInfoObj.get("supplierUserId");
						String supplierLoginId = (String) productInfoObj.get("supplierLoginId");
						String images = "";
						Integer minOrderQuantity = 0;
						String saleType = "";
                        Double width = 0.0;
                        Double height = 0.0;
                        Double length = 0.0;
                        Double unitWeight = 0.0;
						//处理图片
						Map<String, Object> image = (Map<String, Object>) productInfoObj.get("image");
						if (image != null) {
							JSONArray imageArray = (JSONArray) image.get("images");
							if (imageArray != null && imageArray.size() > 0) {
								for (int i = 0; i < imageArray.size(); i++) {
									String itemImg = (String) imageArray.get(i);
									images += "https://cbu01.alicdn.com/" + itemImg + "|";
								}
							}
						}
						//处理最小起订量
						JSONObject saleInfo = productInfoObj.getJSONObject("saleInfo");
						if (saleInfo != null) {
							minOrderQuantity = saleInfo.getInteger("minOrderQuantity");
							saleType = saleInfo.getString("saleType");
						}
                        //处理商品物流信息
                        JSONObject shippingInfo = productInfoObj.getJSONObject("shippingInfo");
                        if (shippingInfo != null) {
                            width =shippingInfo.getDouble("width");
                            height =shippingInfo.getDouble("height");
                            length =shippingInfo.getDouble("length");
                            unitWeight =shippingInfo.getDouble("unitWeight");
                            if((tpProductActive.getSizeWidth() == null || tpProductActive.getSizeWidth().compareTo(BigDecimal.ZERO) == 0) && width != null){
								tpProductActive.setSizeWidth(BigDecimal.valueOf(width));
							}
							if((tpProductActive.getSizeHeight()  == null || tpProductActive.getSizeHeight().compareTo(BigDecimal.ZERO) == 0)  && height != null){
								tpProductActive.setSizeHeight(BigDecimal.valueOf(height));
							}
							if((tpProductActive.getSizeLength() == null || tpProductActive.getSizeLength().compareTo(BigDecimal.ZERO) == 0) && length != null){
								tpProductActive.setSizeLength(BigDecimal.valueOf(length));
							}
							if((tpProductActive.getSizeWeight() == null || tpProductActive.getSizeWeight().compareTo(BigDecimal.ZERO) == 0) && unitWeight != null){
								tpProductActive.setSizeWeight(BigDecimal.valueOf(unitWeight));
							}
                            tpProductActiveMapper.update(tpProductActive);
                        }
						//处理SKU
						List<Map<String, Object>> skuList = (List<Map<String, Object>>) productInfoObj.get("skuInfos");
						if(skuList != null && skuList.size() > 0) {
							for (Map<String, Object> skuItem : skuList) {
								distribution = new TcgDistribution();
								String skuCode = (String) skuItem.get("skuCode");
								String skuId = skuItem.get("skuId").toString();
								String specId = (String) skuItem.get("specId");
								String skuName = "";
								List<Map<String, Object>> skuPropertyList = (List<Map<String, Object>>) skuItem.get("attributes");
								if (skuPropertyList != null && skuPropertyList.size() > 0) {
									for (Map<String, Object> skuNameItem : skuPropertyList) {
										String propValue = (String) skuNameItem.get("attributeValue");
										skuName += propValue + ";";
									}
								}
								if (!StringUtils.isEmpty(skuName) && skuName.length() > 0) {
									skuName = skuName.substring(0, skuName.length() - 1);
								}
								distribution.setGoodsId(productID);
								distribution.setSupplierId(supplierUserId);
								distribution.setSupplierLoginId(supplierLoginId);
								distribution.setSkuId(skuId);
								distribution.setSpecId(specId);
								distribution.setName(subject);
								distribution.setState(status);
								distribution.setImages(images);
								distribution.setSkuCode(skuCode);
								distribution.setSkupRoperty(skuName);
								distribution.setMinNum(minOrderQuantity);
								distribution.setSalesMethod(saleType);
								distribution.setAname(get1688ResourceOwner());
								distribution.setPcode(tpProductActive.getCode());
								distribution.setPname(tpProductActive.getName());
								distribution.setCreateUser("0000");
								insertDataList.add(distribution);
							}
						}else {//没有SKU插入一条SKUID跟商品ID一样，specId为空的数据
							distribution = new TcgDistribution();
							distribution.setGoodsId(productID);
							distribution.setSupplierId(supplierUserId);
							distribution.setSupplierLoginId(supplierLoginId);
							distribution.setSkuId(productID);
							distribution.setSpecId("");
							distribution.setName(subject);
							distribution.setState(status);
							distribution.setImages(images);
							distribution.setSkuCode(productID);
							distribution.setSkupRoperty("");
							distribution.setMinNum(minOrderQuantity);
							distribution.setSalesMethod(saleType);
							distribution.setAname(get1688ResourceOwner());
							distribution.setPcode(tpProductActive.getCode());
							distribution.setPname(tpProductActive.getName());
							distribution.setCreateUser("0000");
							insertDataList.add(distribution);
						}
						int insertLength = insertDataList.size();
						int i = 0;
						while (insertLength > 100) {
							purchaseMapper.insertBatchDistribution(insertDataList.subList(i, i + 100));
							i = i + 100;
							insertLength = insertLength - 100;
						}
						if (insertLength > 0) {
							purchaseMapper.insertBatchDistribution(insertDataList.subList(i, i + insertLength));
						}
					}
					prodResult = true;
				} else {
					prodResult = false;
					String errorMsg = "";
					if (pushJsonObject.containsKey("message")) {
						errorMsg = pushJsonObject.getString("message");
					}
					if (pushJsonObject.containsKey("errorMsg")) {
						errorMsg = pushJsonObject.getString("errorMsg");
					}
					apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(pushPostParams), JSON.toJSONString(pushJsonObject), 400, "调用1688将商品加入铺货列表接口出错，具体错误为:" + errorMsg);
				}
			}
		} catch (Exception ex) {
			//logger.error("ECP_API调用获取1688商品[" + String.valueOf(productId) + "]信息接口产出错，错误信息为：" + ex.getMessage());
			logger.error("ECP_API调用获取1688商品[" + String.valueOf(productId) + "]信息接口产出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "获取1688商品信息-productNo：" + String.valueOf(productId) + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用获取1688商品[" + String.valueOf(productId) + "]信息接口产出错，错误信息为：" + ex.getMessage());
		}
		return prodResult;
	}


	/**
	 * 调用1688相应业务接口时，获取已存在的token值
	 *
	 * @return
	 */
	private String getCacheAccessToken() {
		String tokenExpiresKey = "access_token_Expires";
		String tokenKey = "access_token_1688";
		String token = "";
		if (CacheUtils.get(tokenExpiresKey) == null || CacheUtils.get(tokenExpiresKey).equals("") || new Date().after((Date) CacheUtils.get(tokenExpiresKey))) {//缓存中不存在凭证有效期或失效
			//1688token过期，需要从数据库获取到refresh_token，重新获取新的token值
			TsApi1688ToKen queryApi1688ToKen = new TsApi1688ToKen().queryFirst();
			if (queryApi1688ToKen != null) {//cache缓存中token过期，通过refreshtoken去获取新的token
				String redirectUrl = AppConstant.REFRESH_TOKEN_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey()).replace("YOUR_APPSECRET", MyConfig.get1688AppSecret()).replace("REFRESH_TOKEN", queryApi1688ToKen.getRefreshToken());
				String str = HttpUtil.sendGet(redirectUrl,"utf8");
				JSONObject jsonObject = JSONObject.parseObject(str);
				logger.error("通过refresh_token值获取新的token结果为" + jsonObject);
				if (jsonObject != null) {
					boolean success = true;
					if (jsonObject.containsKey("success")) {
						success = jsonObject.getBoolean("success");
					}
					if(success == true) {
						token = jsonObject.getString("access_token");
						queryApi1688ToKen.setId(queryApi1688ToKen.getId());
						queryApi1688ToKen.setAccessToken(token);
						tsApi1688ToKenMapper.update(queryApi1688ToKen);

						CacheUtils.put(tokenKey, token);//刷新获取最新凭证，存在缓存
						CacheUtils.put(tokenExpiresKey, new Date(System.currentTimeMillis() + 60 * 60 * 1000 * 9));//设置凭证有效期为当前时间+9小时
					}
				}
			}
		} else {
			token = CacheUtils.get(tokenKey).toString();
		}
		return token;
	}


	@Override
	public String get1688ResourceOwner() {
		return "ease逸思电商";
	}

	/**
	 * 创建1688订单
	 * @param orderNos 采购订单号，多个单号用,隔开
	 * @param userId
	 * @returnTcgPurchaseByOrder
	 */
    @Override
    public R create1688Order(String orderNos) {
//        ApiResponse apiResponse = new ApiResponse();
        try {
            if (StringUtils.isEmpty(orderNos)) {
                return R.error("orderNos与userId不能为空！");
            }
            String[] orderNoList = orderNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            /*
             * 发票类型
             */
            Map<String, Object> invoiceParam = null;
            //从公司中取到1688收货地址与发票等信息
            //创建收货地址信息
            //1、先根据orderNo查询采购订单数据
            for (String item : orderNoList) {

                if (StringUtils.isEmpty(item)) {//订单号为空，直接跳过
                    continue;
                }

                TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(item).queryFirst();
                TcgPurchaseByPlan purchasePlan = new TcgPurchaseByPlan().setBid(purchaseOrder.getPlanBid()).queryFirst();
                TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setId(purchasePlan.getPurchaseAddressId()).queryFirst();
                ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(purchasePlan.getVgsbm()).queryFirst();
                
                Map<String, Object> addressParam = new HashMap<>();
                addressParam.put("fullName", thrOperateCompanyApply.getVgsjc());
                addressParam.put("mobile", tcgPurchaseAddress.getVFhrSj());
                addressParam.put("phone", tcgPurchaseAddress.getPhone());
                addressParam.put("postCode", tcgPurchaseAddress.getVYbH());
                addressParam.put("provinceText", tcgPurchaseAddress.getVSfH());
                addressParam.put("cityText", tcgPurchaseAddress.getVDsH());
                addressParam.put("areaText", tcgPurchaseAddress.getVCqH());
                addressParam.put("townText", "");
                addressParam.put("address", tcgPurchaseAddress.getAddress());
                //当发票设置类型不为-1时，创建发票信息
                if (!tcgPurchaseAddress.getInvoiceType().equals("-1")) {
                    invoiceParam = new HashMap<>();
                    invoiceParam.put("invoiceType", tcgPurchaseAddress.getInvoiceType());
                    invoiceParam.put("fullName", tcgPurchaseAddress.getVSpr());
                    invoiceParam.put("mobile", tcgPurchaseAddress.getVSprSj());
                    invoiceParam.put("phone", tcgPurchaseAddress.getVSprDh());
                    invoiceParam.put("postCode", tcgPurchaseAddress.getVYbP());
                    invoiceParam.put("provinceText", tcgPurchaseAddress.getVSfP());
                    invoiceParam.put("cityText", tcgPurchaseAddress.getVDsP());
                    invoiceParam.put("areaText", tcgPurchaseAddress.getVCqP());
                    invoiceParam.put("townText", "");
                    invoiceParam.put("address", tcgPurchaseAddress.getVDzP());
                    invoiceParam.put("companyName", thrOperateCompanyApply.getVgsmc());
                    invoiceParam.put("taxpayerIdentifier", tcgPurchaseAddress.getVTax());
                    if (tcgPurchaseAddress.getInvoiceType().equals("1")) {
                        invoiceParam.put("bankAndAccount", (StringUtils.isEmpty(tcgPurchaseAddress.getVBank()) ? "" : tcgPurchaseAddress.getVBank()) + (StringUtils.isEmpty(tcgPurchaseAddress.getVAccount()) ? "" : tcgPurchaseAddress.getVAccount()));
                        invoiceParam.put("localInvoiceId", "");
                    }
                }

                boolean result;
                if (purchaseOrder.getAliResult().equals("创建成功")){
                    result = false;
                }else{
                    result = sendOrderDataTo1688(item, addressParam, invoiceParam);
					//get1688OrderDetail(orderNos);
                }
                if (!result) {
                    errorNoList.add(item);
                }
            }

            String message = "创建成功";
            if (errorNoList.size() > 0) {
                message = message + "，其中失败的订单号为[" + String.join(",", errorNoList) + "]";
            }
            return R.error(message);
        } catch (Exception ex) {
        	//ex.printStackTrace();
            logger.error("ECP_API调用创建1688采购订单接口出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
            return R.error("ECP_API调用创建1688采购订单接口出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 单条创建1688订单
     *
     * @param orderNo 采购订单号
     * @param userId
     * @return
     */
    private boolean sendOrderDataTo1688(String orderNo, Map<String, Object> addressParam, Map<String, Object> invoiceParam) {
        boolean sendResult = false;
        Map<String, Object> updateMap = new HashMap<>();
        //1、先根据orderNo查询采购订单数据
        TcgPurchaseByOrder order = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
        if (order == null) {
            return false;
        }
        //对于已创建到1688的订单，直接返回true，不再重复创建
        if (!StringUtils.isEmpty(order.getAliOrderNumber())) {
            //return true;
        }
        //商品信息
        List<Map<String, Object>> cargoParamList = new ArrayList<>();
        Map<String, Object> cargoParamItem = null;
        List<TcgPurchaseByOrderSon> orderItemList = new TcgPurchaseByOrderSon().setPid(order.getId()).queryList();
        String message = "";
        if (orderItemList != null && orderItemList.size() > 0) {
            for (TcgPurchaseByOrderSon orderItem : orderItemList) {
            	TcgPurchaseByPlanSon tcgPurchasePlanSon = new TcgPurchaseByPlanSon().setId(orderItem.getPurchasePlanSonId()).queryFirst();
                //订单留言信息
                if (!StringUtils.isEmpty(tcgPurchasePlanSon.getSubRemark())) {
                    message += tcgPurchasePlanSon.getSubRemark() + ",";
                }

                cargoParamItem = new HashMap<>();
                
                if (!StringUtils.isEmpty(orderItem.getSpecId())) {
                    cargoParamItem.put("specId", orderItem.getSpecId());
				}
                cargoParamItem.put("quantity", tcgPurchasePlanSon.getSubTotalAmount());
                cargoParamItem.put("offerId", orderItem.getGoodsId());
                cargoParamList.add(cargoParamItem);
            }
        }
        //3、创建相应的post参数
        Map<String, String> postParams = new HashMap<>();
        String token = getCacheAccessToken();
        long aop_timestamp = new Date().getTime();
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        postParams.put("access_token", token);
        postParams.put("flow", "general");//流程
        postParams.put("tradeType", "assureTrade");// 交易类型-交易4.0通用担保交易
        //留言
        if (!StringUtils.isEmpty(message) && message.length() > 0) {
            postParams.put("message", message.substring(0, message.length() - 1));
        } else {
            postParams.put("message", "");
        }
        postParams.put("cargoParamList", JSON.toJSONString(cargoParamList));
        //收货地址
        if (addressParam != null) {
			addressParam.put("address", order.getApiAddrSend());
			postParams.put("addressParam", JSON.toJSONString(addressParam));
        }
        //发票信息
        if (invoiceParam != null) {
            postParams.put("invoiceParam", JSON.toJSONString(invoiceParam));
        }
        
        // 店铺优惠ID
        if (order.getAliPromotionId() != null && order.getAliPromotionId().length() > 0) {
            postParams.put("aliPromotionId", order.getAliPromotionId());
		}
        
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.createCrossOrder/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
            if (StringUtils.isEmpty(token)){
            	apiLogService.addApiLog("1688", "Create1688Order", "1688订单创建-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
                return false;
            }
            String url = AppConstant.CREATE_ORDER_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
            logger.info("创建1688订单返回："+jsonObject);
            String errorMsg = "";
            if (jsonObject != null) {
                updateMap.put("bid", orderNo);
                updateMap.put("aliMessage", message);
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                JSONObject orderResult = (JSONObject) jsonObject.get("result");
                if (success == true) {//成功处理
                    if (orderResult != null) {
                        String aliOrderNumber = orderResult.getString("orderId");
                        Long orderAmount = orderResult.getLong("totalSuccessAmount");
                        Long freightCharge = orderResult.getLong("postFee");
                        boolean itemSuccess = orderResult.getBoolean("success");
                        if (itemSuccess == true) {//订单内部正确标记
                            BigDecimal orderAmountBig = BigDecimal.valueOf(orderAmount).divide(new BigDecimal(100));
                            sendResult = true;

                            //更新订单的返回数据
                            order.setAliResult("创建成功")
                            	.setAliState("waitbuyerpay")
                            	.setAliOrderNumber(aliOrderNumber)
                            	.setOrderAmount(new BigDecimal(orderAmount))
								.setOrderAmountDiscuss(new BigDecimal(orderAmount))
                            	.setFreightCharge(BigDecimal.valueOf(freightCharge).divide(new BigDecimal(100)))

                            	.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value);
//                            if(order.getPurchaseOrderAmount()==null){
//								order.setPurchaseOrderAmount(order.getOrderAmount().multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_HALF_UP));//采购订单金额（含税）,默认等于：实际订单金额（含运）
//							}

                            //order.setServiceCharge(order.getPurchaseOrderAmount().multiply(new BigDecimal("0.05")).setScale(2, BigDecimal.ROUND_HALF_UP));
							tcgPurchaseByOrderMapper.update(order);
							//同步
							get1688OrderDetailByApi(orderNo);
                        } else {
                            String itemMessage = orderResult.getString("message");
                            errorMsg = "创建订单失败，错误信息为：" + itemMessage;
                            JSONArray failedOfferList = orderResult.getJSONArray("failedOfferList");
                            if (failedOfferList != null && failedOfferList.size() > 0) {
                                errorMsg = errorMsg + "，具体商品失败信息如下：\n\r";
                                for (int i = 0; i < failedOfferList.size(); i++) {
                                    JSONObject failedItem = failedOfferList.getJSONObject(i);
                                    String itemOfferId = failedItem.getString("offerId");
                                    String itemSpecId = failedItem.getString("specId");
                                    String itemErrorMessage = failedItem.getString("errorMessage");
                                    errorMsg += "商品编号[" + itemOfferId + "]的下的specId为[" + itemSpecId + "]下单失败，具体错误为：" + itemErrorMessage + "\n\r";
                                }
                            }
                            sendResult = false;

                            //更新订单的返回数据
                            order.setAliResult("创建失败")
                            	.setAliErrorMessages(errorMsg)
								.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_FAIL.value)
							;
							tcgPurchaseByOrderMapper.update(order);
                        }
                    }
                } else {//失败处理
                    if (jsonObject.containsKey("message")) {
                        errorMsg = jsonObject.getString("message");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    if (orderResult != null) {
                        JSONArray failedOfferList = orderResult.getJSONArray("failedOfferList");
                        if (failedOfferList != null && failedOfferList.size() > 0) {
                            errorMsg = errorMsg + "，具体失败信息如下：\n\r";
                            for (int i = 0; i < failedOfferList.size(); i++) {
                                JSONObject failedItem = failedOfferList.getJSONObject(i);
                                String itemSkuId = failedItem.getString("offerId");
                                String itemErrorMessage = failedItem.getString("errorMessage");
                                errorMsg += "商品[" + itemSkuId + "]下单失败，具体错误为：" + itemErrorMessage + "\n\r";
                            }
                        }
                    }
                    sendResult = false;

                    //更新订单的返回数据
                    order.setAliResult("创建失败")
                    	.setAliErrorMessages(errorMsg);
					tcgPurchaseByOrderMapper.update(order);
                }
                
//                //更新订单的返回数据
//                purchaseOrderMapper.updatePurchaseOrderToCreateOrder(updateMap);
            }
        } catch (Exception ex) {
            logger.error("ECP_API调用创建1688采购订单接口创建[" + orderNo + "]出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
            apiLogService.addApiLog("1688", "Create1688Order", "1688订单创建-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用创建1688采购订单接口创建[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
        }
        return sendResult;
    }

    @Override
    public R cancel1688Order(String orderNos, String cancelReason,boolean planIsCancel) {
        try {
            if (StringUtils.isEmpty(cancelReason)) {
            	return R.error("取消原因不能为空！");
            }
            String[] orderNoList = orderNos.split(",");
            List<String> errorNoList = new ArrayList<>();
            for (String orderNo : orderNoList) {
                boolean result = cancelOrderDataTo1688(orderNo, cancelReason,planIsCancel);
                if (result == false) {
                    errorNoList.add(orderNo);
                }
            }
            String message = "1688取消采购订单操作成功";
            if (errorNoList.size() > 0) {
                message = message + "，其中1688接口取消失败的订单号为[" + String.join(",", errorNoList) + "]";
            }
            return R.ok(message,errorNoList);
         } catch (Exception ex) {
            logger.error("ECP_API调用取消1688采购订单接口出错，错误信息为：" + ex.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
       	 	return R.error("ECP_API调用取消1688采购订单接口出错，具体错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 单条取消1688订单
     *
     * @param orderNo
     * @param userId
     * @param cancelReason
     * @param system
     * @param type
     * @return
     */
    private boolean cancelOrderDataTo1688(String orderNo, String cancelReason,boolean planIsCancel) {
        boolean sendResult = false;
        Map<String, Object> updateMap = new HashMap<>();
        //1、先根据orderNo查询采购订单数据
        TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
        if (purchaseOrder == null) {
            return false;
        }
        if (StringUtils.isEmpty(purchaseOrder.getAliOrderNumber())) {
        	//更新订单的返回数据
        	purchaseOrder.setAliResult("取消失败")
        		.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null ?purchaseOrder.getAliErrorMessages(): "")+"【取消1688订单失败】此订单没有1688的订单编号");
			tcgPurchaseByOrderMapper.update(purchaseOrder);
        	return false;
        }
        Map<String, String> postParams = new HashMap<>();
        String token = getCacheAccessToken();
        long aop_timestamp = new Date().getTime();
        postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
        postParams.put("access_token", token);
        postParams.put("webSite", "1688");
        postParams.put("tradeID", purchaseOrder.getAliOrderNumber());
        postParams.put("cancelReason", "other");
        postParams.put("remark", cancelReason);
        String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.cancel/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
        postParams.put("_aop_signature", aop_signature);
        try {
            apiLogService.addApiLog("1688", "Cancel1688Order", "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 0, "");
            if (StringUtils.isEmpty(token)){
            	apiLogService.addApiLog("1688", "Cancel1688Order", "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
               return false;
            }
            String url = AppConstant.CANCEL_ORDER_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
            JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
			logger.info("1688取消返回："+jsonObject);
            String errorMsg = "";
            if (jsonObject != null) {
                boolean success = false;
                if (jsonObject.containsKey("success")) {
                    success = jsonObject.getBoolean("success");
                }
                //1688订单已取消，本地数据状态未变更的情况
				if (jsonObject.get("errorCode")!=null) {
					if(jsonObject.get("errorCode").toString().equals("400_5") && jsonObject.get("errorMessage").toString().equals("该订单已经取消")){
						success = true;
					}
				}
                updateMap.put("bid", orderNo);
                if (success == true) {
                    updateMap.put("aliResult", "取消成功");
                    updateMap.put("aliOrderNumber", "");
                    updateMap.put("orderAmount", 0);
                    updateMap.put("freightCharge", 0);
                    updateMap.put("orderAmount2", 0);
                    updateMap.put("freightCharge2", 0);
                    updateMap.put("serviceCharge", 0);
                    updateMap.put("aliMessage", "");
                    updateMap.put("aliState", "");
                    updateMap.put("aliErrorMessages", "");
                    sendResult = true;
                    
                	//更新订单的返回数据
                	//purchaseOrder.setAliResult("取消成功").setAliState("cancel");
                		//.setAliOrderNumber("")
                		//.setServiceCharge(BigDecimal.ZERO)

                		//.setAliErrorMessages("");
                	//tcgPurchaseByOrderMapper.update(purchaseOrder);
					tcgPurchaseByOrderService.cancelOrderByOneRow(purchaseOrder.getPurchasePlanGoodsId(),purchaseOrder.getPlanBid(),purchaseOrder.getOperateStatus(),purchaseOrder.getOrderStatus(),cancelReason,planIsCancel);
                } else {
                    if (jsonObject.containsKey("errorMessage")) {
                        errorMsg = jsonObject.getString("errorMessage");
                    }
                    if (jsonObject.containsKey("error_message")) {
                        errorMsg = jsonObject.getString("error_message");
                    }
                    updateMap.put("aliResult", "取消失败");
                    updateMap.put("aliErrorMessages", errorMsg);
                    sendResult = false;
                    
                	//更新订单的返回数据
                	purchaseOrder.setAliResult("取消失败")
                		.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null ?purchaseOrder.getAliErrorMessages(): "")+"【取消1688订单失败】"+errorMsg);
					tcgPurchaseByOrderMapper.update(purchaseOrder);
                }
            }
        } catch (Exception ex) {
            logger.error("ECP_API调用取消1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
            apiLogService.addApiLog("1688", "Cancel1688Order", "1688订单取消-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用创建1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
        }
        return sendResult;
    }

	@Override
	public R get1688Token(String code) {
		if (StringUtils.isEmpty(code)) {
			return R.error("通过code换取token时，code值不能为空！");
		}
		String tokenExpiresKey = "access_token_Expires";
		String tokenKey = "access_token_1688";
		String redirectUrl = AppConstant.ACCESS_TOKEN_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey()).replace("YOUR_APPSECRET", MyConfig.get1688AppSecret()).replace("YOUR_REDIRECT_URI", "").replace("CODE", code);
		String result = HttpUtil.sendGet(redirectUrl);
		logger.info("通过code值[" + code + "]值获取到的token结果为" + result);
		TsApi1688ToKen model = null;
		if (result != null && result.length() > 0) {
			JSONObject jsonObject = JSON.parseObject(result);
			String access_token = jsonObject.getString("access_token");
			String aliId = jsonObject.getString("aliId");
			String refresh_token = jsonObject.getString("refresh_token");
			String resource_owner = jsonObject.getString("resource_owner");
			String expires_in = jsonObject.getString("expires_in");
			String refresh_token_timeout = jsonObject.getString("refresh_token_timeout");
			String memberId = jsonObject.getString("memberId");
			Date refreshTokenDate = null;
			//处理刷新token过期时间，转换成正常的时间格式
			if (!StringUtils.isEmpty(refresh_token_timeout) && refresh_token_timeout.length() >= 8) {
				String refresh_token_timeout2 = refresh_token_timeout.substring(0, refresh_token_timeout.length() - 8);
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
				LocalDateTime localDate = LocalDateTime.parse(refresh_token_timeout2, formatter);
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
				try {
					refreshTokenDate = simpleDateFormat.parse(localDate.toString());
				} catch (Exception ex) {
				}
			}
			CacheUtils.put(tokenKey, access_token);//获取最新凭证
			CacheUtils.put(tokenExpiresKey, new Date(System.currentTimeMillis() + 60 * 60 * 1000 * 9));//设置凭证有效期为当前时间+9小时
			TsApi1688ToKen queryApi1688ToKen = new TsApi1688ToKen().queryFirst();
			if (queryApi1688ToKen == null) {
				model = new TsApi1688ToKen();
				model.setAccessToken(access_token);
				model.setAliId(aliId);
				model.setRefreshToken(refresh_token);
				model.setResourceOwner(resource_owner);
				model.setExpiresIn(expires_in);
				model.setRefreshTokenTimeout(refresh_token_timeout);
				model.setMemberId(memberId);
				model.setRefreshTokenDate(refreshTokenDate);
				tsApi1688ToKenMapper.insert(model);
			} else {
				model = new TsApi1688ToKen();
				model.setId(queryApi1688ToKen.getId());
				model.setAccessToken(access_token);
				model.setAliId(aliId);
				model.setRefreshToken(refresh_token);
				model.setResourceOwner(resource_owner);
				model.setExpiresIn(expires_in);
				model.setRefreshTokenTimeout(refresh_token_timeout);
				model.setMemberId(memberId);
				model.setRefreshTokenDate(refreshTokenDate);
				tsApi1688ToKenMapper.update(model);
			}
			return R.ok("通过code换取token成功！");
		} else {
			return R.ok("通过code换取token失败！");
		}
	}

	@Override
	@Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
	public R get1688OrderDetail(String orderNos) {
		try {
			if (StringUtils.isEmpty(orderNos)) {
				return R.error("订单号不能为空！");
			}
			String[] orderNoList = orderNos.split(",");
			List<String> errorNoList = new ArrayList<>();
			for (String orderNo : orderNoList) {
				boolean result = get1688OrderDetailByApi(orderNo);
				if (result == false) {
					errorNoList.add(orderNo);
				}
			}
			String message = "获取1688订单信息操作成功";
			if (errorNoList.size() > 0) {
				message = message + "，其中获取失败的订单号为[" + String.join(",", errorNoList) + "]";
			}
			return R.ok(message);
		} catch (Exception ex) {
			logger.error("获取1688订单信息操作出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("获取1688订单信息操作出错，具体错误信息为：" + ex.getMessage());
		}
	}

	/**
	 * 单条获取1688订单信息
	 */
	private boolean get1688OrderDetailByApi(String orderNo) {
		boolean sendResult = false;
		//1、先根据orderNo查询采购订单数据
		TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
		if (purchaseOrder == null) {
			return false;
		}
		if (StringUtils.isEmpty(purchaseOrder.getAliOrderNumber())) {
			//更新订单的返回数据
			purchaseOrder.setAliResult("获取失败")
					.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null?purchaseOrder.getAliErrorMessages():"")+"【同步订单失败】此订单没有1688的订单编号");
			tcgPurchaseByOrderMapper.update(purchaseOrder);
			return false;
		}
		Map<String, String> postParams = new HashMap<>();
		String token = getCacheAccessToken();
		long aop_timestamp = new Date().getTime();
		postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
		postParams.put("access_token", token);
		postParams.put("webSite", "1688");
		postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660419985562523597"
		String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.get.buyerView/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
		postParams.put("_aop_signature", aop_signature);
		try {
			if (StringUtils.isEmpty(token)){
				logger.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				apiLogService.addApiLog("1688", "Get1688OrderDetail", "1688订单信息-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				return false;
			}
			String url = AppConstant.GET_ORDERDETAIL_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
			JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
			String errorMsg = "";
			if (jsonObject != null) {
				String success = "";
				if (jsonObject.containsKey("success")) {
					success = jsonObject.getString("success");
				}
				if (success.toLowerCase().equals("true")) {
					sendResult = true;
					JSONObject orderResult = (JSONObject) jsonObject.get("result");
					if (orderResult != null) {
						logger.info("ECP_API调用获取1688采购订单接口成功!" + orderResult);
						JSONObject baseInfo = (JSONObject) orderResult.get("baseInfo");
						//获取可以进行订单同步的状态
						List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getRefreshStatus();
						//验证状态
						boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,purchaseOrder.getOrderStatus());
						//订单状态信息
						if (baseInfo != null) {
							purchaseOrder.setAliState(baseInfo.getString("status"));


							purchaseOrder.setCouponFee(baseInfo.getString("couponFee")!=null?new BigDecimal(baseInfo.getString("couponFee")):BigDecimal.ZERO);//红包金额
							if(statusIsPass) {//2024-10-11 当状态为订单已创建\已生成 更新数据
								BigDecimal orderAmountBig = baseInfo.getBigDecimal("totalAmount");
								purchaseOrder.setOrderAmount(orderAmountBig);
								JSONArray newStepOrderList = null;
								if(baseInfo.get("newStepOrderList")!=null){
									newStepOrderList = baseInfo.getJSONArray("newStepOrderList");
								}

								if(purchaseOrder.getPurchaseOrderAmount()==null){
									//累计店铺+plus优惠
									BigDecimal discountFee = BigDecimal.ZERO;//（店铺+plus优惠）
									if(newStepOrderList!=null && newStepOrderList.size()>0){
										for(int i=0;i<newStepOrderList.size();i++){
											JSONObject itemInfo = newStepOrderList.getJSONObject(i);
											if(itemInfo.get("discountFee")!=null){
												discountFee = discountFee.add(new BigDecimal(itemInfo.get("discountFee").toString()));
											}
										}
									}
									BigDecimal purchaseOrderAmount = (orderAmountBig.add(purchaseOrder.getCouponFee().add(discountFee))).setScale(2, BigDecimal.ROUND_HALF_UP);
									logger.info("ECP_API调用获取1688采购订单接口，计算采购订单金额（含税）：purchaseOrderAmount = " + purchaseOrderAmount +"="+ orderAmountBig+"+"+purchaseOrder.getCouponFee()+"+"+discountFee);
									purchaseOrder.setPurchaseOrderAmount(purchaseOrderAmount);//采购订单金额（含税）,默认等于：实际订单金额（含运）
								}

								purchaseOrder.setOrderAmountDiscuss(orderAmountBig);
								purchaseOrder.setAliAccount(get1688ResourceOwner());//1688账号
								purchaseOrder.setFreightCharge(baseInfo.getBigDecimal("shippingFee"));
                                purchaseOrder.setServiceCharge((purchaseOrder.getPurchaseOrderAmount().multiply(new BigDecimal("0.05")).setScale(2, BigDecimal.ROUND_HALF_UP)));
                                //purchaseOrder.setServiceCharge((orderAmountBig.multiply(new BigDecimal("0.05")).setScale(2, BigDecimal.ROUND_HALF_UP)));
								//获取 1688回调需要修改订单状态
								List<TcgPurchaseByOrderEnum.OrderStatus> get1688RefreshAndUpdateStatus = TcgPurchaseByOrderEnum.OrderStatus.get1688RefreshAndUpdateStatus();
								//验证状态
								boolean isPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(get1688RefreshAndUpdateStatus,purchaseOrder.getOrderStatus());
								if(isPass){
									purchaseOrder.setOrderStatus(purchaseOrder.getCouponFee().compareTo(BigDecimal.ZERO)==0?TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value:TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_WITH_COUPON.value);
								}
								/*
								if(purchaseOrder.getOrderStatus().equals(TcgPurchaseByOrderEnum.OrderStatus.ORDER_PRODUCE.value)
                                || purchaseOrder.getOrderStatus().equals(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value)
								|| purchaseOrder.getOrderStatus().equals(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_WITH_COUPON.value)){
									purchaseOrder.setOrderStatus(purchaseOrder.getCouponFee().compareTo(BigDecimal.ZERO)==0?TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value:TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_WITH_COUPON.value);
                                }
								 */
							}
						}
						//物流信息
						JSONObject nativeLogistics = (JSONObject) orderResult.get("nativeLogistics");
						if (nativeLogistics != null) {
							JSONArray logisticsItems = (JSONArray) nativeLogistics.get("logisticsItems");
							String aliLogisticsCompanyCode = "";
							if (logisticsItems != null && logisticsItems.size() > 0) {
								for (int i = 0; i < logisticsItems.size(); i++) {
									JSONObject logisticsItem = logisticsItems.getJSONObject(i);
									aliLogisticsCompanyCode += logisticsItem.getString("logisticsCompanyNo") + ',';
								}
								if (aliLogisticsCompanyCode.length() > 0) {
									aliLogisticsCompanyCode = aliLogisticsCompanyCode.substring(0, aliLogisticsCompanyCode.length() - 1);
								}
								purchaseOrder.setAliLogisticsCompanyCode(aliLogisticsCompanyCode);
							}
						}
						tcgPurchaseByOrderMapper.update(purchaseOrder);
						//处理订单商品信息价格
						if(statusIsPass) {//2024-10-11 当状态为订单已创建 更新数据
							JSONArray productItems = (JSONArray) orderResult.get("productItems");
							if (productItems != null && productItems.size() > 0) {

								for (int j = 0; j < productItems.size(); j++) {
									JSONObject productItem = productItems.getJSONObject(j);
									if (productItem != null) {
										String specId = productItem.getString("specId");
										String skuId = productItem.getString("skuID");
										String productID = productItem.getString("productID");
										Double price2 = productItem.getDouble("price");
										//BigDecimal realityCost = BigDecimal.ZERO;
										//查询采购订单子件信息
										TcgPurchaseByOrderSon tcgPurchaseOrderSon = null;

										if(skuId!=null && specId!=null){
											tcgPurchaseOrderSon = new TcgPurchaseByOrderSon()
													.setSpecId(specId)
													.setSkuId(skuId).setPid(purchaseOrder.getId())
													.queryFirst();
											if(tcgPurchaseOrderSon==null){
												purchaseOrder.setAliResult("获取失败")
														.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null?purchaseOrder.getAliErrorMessages():"")+"【同步订单失败】此订单的铺货信息有误，请校对；skuId="+skuId+"；specId="+specId);
												tcgPurchaseByOrderMapper.update(purchaseOrder);
												//continue;
												return false;
											}
										}else {
											if(productID!=null){
												tcgPurchaseOrderSon = new TcgPurchaseByOrderSon()
														.setGoodsId(productID)
														.setPid(purchaseOrder.getId())
														.queryFirst();
												if(tcgPurchaseOrderSon==null){
													purchaseOrder.setAliResult("获取失败")
															.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null?purchaseOrder.getAliErrorMessages():"")+"【同步订单失败】此订单的铺货信息有误，请校对；skuId="+skuId+"；specId="+specId);
													tcgPurchaseByOrderMapper.update(purchaseOrder);
													//continue;
													return false;
												}
											}else {
												purchaseOrder.setAliResult("获取失败")
														.setAliErrorMessages((purchaseOrder.getAliErrorMessages()!=null?purchaseOrder.getAliErrorMessages():"")+"【同步订单失败】此订单的铺货信息有误，请校对；skuId、specId、1688铺货商品ID都为空");
												tcgPurchaseByOrderMapper.update(purchaseOrder);
												//continue;
												return false;
											}
										}


										tcgPurchaseOrderSon.setRealityPrice(new BigDecimal(price2).setScale(3, RoundingMode.HALF_UP));
										//tcgPurchaseOrderSon.setRealityCost(realityCost);
										//计算子件实际单价、总价信息
										//tcgPurchaseOrderSon = tcgPurchaseByOrderService.countSubRealityPrice(purchaseOrder,tcgPurchaseOrderSon);
										//tcgPurchaseOrderSon.setSubRealityPrice(subRealityPrice);

										//增加获取下单后获取SKU属性进行对比
										JSONArray skuInfos = (JSONArray)productItem.get("skuInfos");
										if (skuInfos != null && skuInfos.size() > 0){
											String realitySku = "";
											for (int k = 0; k < skuInfos.size(); k++) {
												JSONObject skuInfoItem = skuInfos.getJSONObject(k);
												realitySku += skuInfoItem.getString("value")+";";
											}
											if (!StringUtils.isEmpty(realitySku) && realitySku.length() > 0){
												realitySku = realitySku.substring(0, realitySku.length()-1);
											}
											tcgPurchaseOrderSon.setRealitySku(realitySku);
										}
										logger.info("tcgPurchaseOrderSon："+tcgPurchaseOrderSon);
										tcgPurchaseByOrderSonMapper.update(tcgPurchaseOrderSon);
										TpProductActiveComponent tpProductActiveComponent = new TpProductActiveComponent().setCode(tcgPurchaseOrderSon.getSubCode()).queryFirst();
										tpProductActiveComponent.setBprice(BigDecimal.valueOf(price2));
										tpProductActiveComponentMapper.update(tpProductActiveComponent);
										TpProductBasisComponent tpProductBasisComponent = new TpProductBasisComponent().setCode(tcgPurchaseOrderSon.getSubCode()).queryFirst();
										tpProductBasisComponent.setBprice(BigDecimal.valueOf(price2));
										tpProductBasisComponentMapper.update(tpProductBasisComponent);

									}
								}


								//计算子件实际单价、总价信息
								tcgPurchaseByOrderService.countSubRealityPrice(purchaseOrder);

								//修改订单管理状态
								tcgPurchaseByOrderService.updateOrderManageStatus(purchaseOrder.getBid());


							}
						}
					}
				}
			}
		} catch (Exception ex) {
			//logger.error("ECP_API调用获取1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
			logger.error("ECP_API调用获取1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			apiLogService.addApiLog("1688", "Get1688OrderDetail", "1688订单获取-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用获取1688采购订单接口取消[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
		}
		return sendResult;
	}

	@Override
	public R get1688OrderTraceInfo(String orderNo) {
		try {
			if (StringUtils.isEmpty(orderNo)) {
				return R.error("参数orderNo不能为空！");
			}
			TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
			if (purchaseOrder == null) {
				return R.error("订单不存在");
			}
			Map<String, String> postParams = new HashMap<>();
			if (purchaseOrder != null) {
				String token = getCacheAccessToken();
				if (StringUtils.isEmpty(token)){
					return R.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
				}
				long aop_timestamp = new Date().getTime();
				postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
				postParams.put("access_token", token);
				postParams.put("webSite", "1688");
				postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660325666067523597"
				String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsTraceInfo.buyerView/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
				postParams.put("_aop_signature", aop_signature);
				String url = AppConstant.GET_ORDERTRACEINFO_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
				JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
				if (jsonObject == null) {
					logger.error("调用获取1688采购订单物流跟踪信息接口返回不是一个JSON对象，错误信息为：" + JSON.toJSONString(jsonObject));
					apiLogService.addApiLog("1688","get1688OrderTraceInfo" , "orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 1, "请求物流轨迹接口失败!");
					return  R.error("调用获取1688采购订单物流跟踪信息接口返回不是一个JSON对象！");
				}
				boolean success = false;
				if (jsonObject.containsKey("success")) {
					success = jsonObject.getBoolean("success");
				}
				if (success == true) {
					String errorMsg = "";
					if (jsonObject.containsKey("errorMessage")) {
						errorMsg = jsonObject.getString("errorMessage");
					}
					if (!StringUtils.isEmpty(errorMsg)) {
						return R.error(errorMsg);
					} else {
						JSONArray logisticsTrace = (JSONArray) jsonObject.get("logisticsTrace");
						if (logisticsTrace != null && logisticsTrace.size() > 0) {
							//取索引为0的跟踪信息
							JSONObject logisticsTraceItem = logisticsTrace.getJSONObject(0);
							if (logisticsTraceItem != null) {
								JSONArray logisticsSteps = logisticsTraceItem.getJSONArray("logisticsSteps");
								return R.ok("调用获取1688采购订单物流跟踪信息成功",logisticsSteps);
							}else {
								logger.error("调用获取1688采购订单物流跟踪信息成功，错误信息为：" + JSON.toJSONString(logisticsTrace));
								return R.error("调用获取1688采购订单物流跟踪信息接口出错");
							}
						}else {
							logger.error("调用获取1688采购订单物流跟踪信息接口返回不是一个JSON对象logisticsTrace为空，错误信息为：" + JSON.toJSONString(jsonObject));
							return R.error("调用获取1688采购订单物流跟踪信息接口出错");
						}
					}
				} else {
					String errorMsg = "";
					if (jsonObject.containsKey("errorMessage")) {
						errorMsg = jsonObject.getString("errorMessage");
					}
					if (jsonObject.containsKey("error_message")) {
						errorMsg = jsonObject.getString("error_message");
					}
					return R.error("调用获取1688采购订单物流跟踪信息接口出错，具体错误为：" + errorMsg);
				}
			} else {
				return R.error("orderNo单号对应的订单不存在！");
			}
		} catch (Exception ex) {
			//logger.error("ECP_API调用获取1688采购订单物流跟踪信息接口出错，错误信息为：" + ex.getMessage());
			logger.error("ECP_API调用获取1688采购订单物流跟踪信息接口出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			return R.error("ECP_API调用获取1688采购订单物流跟踪信息接口出错，具体错误信息为：" + ex.getMessage());
		}
	}

	@Override
	public R get1688AlipayUrl(String aliOrderNos) {
		try {
			if (StringUtils.isEmpty(aliOrderNos)) {
				return R.error("参数aliOrderNos不能为空！");
			}
			String[] orderNoArray = aliOrderNos.split(",");
			if (orderNoArray.length > 30) {
				return R.error("一次性最多只能支付30个1688订单！");
			}
			Long[] orderIdList = new Long[orderNoArray.length];
			int k = 0;
			for (String orderNo : orderNoArray) {
				if (!StringUtils.isEmpty(orderNo)) {//订单号不为空加入
					orderIdList[k] = TypeUtils.getSafeLong(orderNo, 0L);
					k++;
				}
			}
			Map<String, String> postParams = new HashMap<>();
			String token = getCacheAccessToken();
			if (StringUtils.isEmpty(token)){
				return R.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
			}
			long aop_timestamp = new Date().getTime();
			postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
			postParams.put("access_token", token);
			postParams.put("orderIdList", JSON.toJSONString(orderIdList));
			String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.alipay.url.get/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
			postParams.put("_aop_signature", aop_signature);
			String url = AppConstant.GET_ORDERALIPAY_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
			JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
			if (jsonObject == null) {
				apiLogService.addApiLog("1688", "get1688AlipayUrl", "aliOrderNos：" + aliOrderNos + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 1, "获取付款url失败!");
				return R.error("调用获取1688支付URL接口返回不是一个JSON对象！");
			}
			boolean success = false;
			if (jsonObject.containsKey("success")) {
				success = jsonObject.getBoolean("success");
			}
			if (success == true) {
				String payUrl = jsonObject.getString("payUrl");
				return R.ok("获取1688支付URL成功!",payUrl);
			} else {
				String errorMsg = "";
				if (jsonObject.containsKey("erroMsg")) {
					errorMsg = jsonObject.getString("erroMsg");
				}
				if (jsonObject.containsKey("error_message")) {
					errorMsg = jsonObject.getString("error_message");
				}
				logger.error("调用获取1688支付URL接口出错，具体错误为：" + errorMsg);
				return R.error("调用获取1688支付URL接口出错，具体错误为：" + errorMsg);
			}
		}catch (Exception ex) {
			//logger.error("ECP_API调用获取1688支付URL接口出错，错误信息为：" + ex.getMessage());
			logger.error("ECP_API调用获取1688支付URL接口出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			return R.error("ECP_API调用获取1688支付URL接口出错，具体错误信息为：" + ex.getMessage());
		}
	}

	/**
	 * 回调1688消息
	 * @param dataParams
	 * @return
	 */
	@Override
	public R push1688Message(Map<String, Object> dataParams) {
		synchronized (this) {
			try {
				if (dataParams == null) {
					return R.error("参数dataParams不能为空！");
				}
				String message = (String) dataParams.get("message");
				String aop_signature = (String) dataParams.get("_aop_signature");
				Map<String, String> signParams = new HashMap<>();
				signParams.put("message", message);
				String newSignature = ApiHmacSHA1Utils.signatureWithParamsOnly(signParams, MyConfig.get1688AppSecret());
				if (!newSignature.equals(aop_signature)) {
					logger.error("_aop_signature签名参数验证失败，错误信息为：" + aop_signature);
					apiLogService.addApiLog("1688", "push1688Message", "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(aop_signature), 1, "_aop_signature签名参数验证失败");
					return R.error("_aop_signature签名参数验证失败！");
				}

				Map<String, Object> messageMap = JSONObject.parseObject(message, new TypeReference<Map<String, Object>>() {
				});
				if (messageMap == null) {
					apiLogService.addApiLog("1688", "push1688MessageMap", "dataParams：" + JSON.toJSONString(dataParams), JSON.toJSONString(messageMap), 1, "message参数不是一个有效的JSON字符串");
					return R.error("message参数不是一个有效的JSON字符串！");
				}

				String messageType = (String) messageMap.get("type");
				Map<String, Object> dataMap = (Map<String, Object>) messageMap.get("data");
				switch (messageType) {
					case "ORDER_BATCH_PAY"://批量支付消息处理
						JSONArray batchPayList = (JSONArray) dataMap.get("batchPay");
						if (batchPayList != null && batchPayList.size() > 0) {
							for (int i = 0; i < batchPayList.size(); i++) {
								JSONObject itemObj = batchPayList.getJSONObject(i);
								String orderId1 = (String) itemObj.get("orderId");
								String status1 = (String) itemObj.get("status");
								TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setAliOrderNumber(orderId1).queryFirst();
								if (status1.equals("successed")) {
									//已付款
									purchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_YES.value);
									purchaseOrder.setIsPay(1);
								} else {
									purchaseOrder.setAliResult("支付失败");
									purchaseOrder.setAliErrorMessages(getAliPaymentStateName(status1));
									purchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_FAIL.value);
								}
								R r = get1688AliState(orderId1);
								if (r.getCode() == 0){
									purchaseOrder.setAliState(r.getMsg());
								}
								tcgPurchaseByOrderMapper.update(purchaseOrder);
							}
						}else {
							return R.error("ORDER_BATCH_PAY获取失败");
						}
						break;
					case "ORDER_BUYER_VIEW_ORDER_PAY"://1688交易付款（买家视角)
						String orderId2 = dataMap.get("orderId").toString();
						String status2 = (String) dataMap.get("currentStatus");
						if (status2.equals("waitsellersend")) {//20230303增加判断，只有成功支付,20230313改成判断订单状态为waitsellersend时更新已付款（status2.equals("success"))
							TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setAliOrderNumber(orderId2).queryFirst();
							purchaseOrder.setAliResult("支付成功");
							purchaseOrder.setAliState(status2);
							purchaseOrder.setIsPay(1);
							purchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PAY_YES.value);
							tcgPurchaseByOrderMapper.update(purchaseOrder);
						}
						break;
				}
			} catch (Exception ex) {
				//logger.error("ECP_API处理1688回调消息出错，错误信息为：" + ex.getMessage());
				logger.error("ECP_API处理1688回调消息出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
				return R.error("ECP_API处理1688回调消息出错，具体错误信息为：" + ex.getMessage());
			}
		}
		return R.ok("1688回调成功!");
	}

	/**
	 * 获取1688支付状态中英信息
	 *
	 * @param payState
	 * @return
	 */
	private String getAliPaymentStateName(String payState) {
		String resultName = "";
		if (payState.toUpperCase().contains("ACCOUNT_BALANCE_NOT_ENOUGH")) {
			resultName = payState + "-余额不足";
		} else if (payState.toUpperCase().contains("ACCOUNT_NOT_EXIST")) {
			resultName = payState + "-跨境宝2.0场景下可能签约但是在ipay没有开户";
		} else if (payState.toUpperCase().contains("ACCOUNT_FROZEN")) {
			resultName = payState + "-账户冻结";
		} else if (payState.toUpperCase().contains("PARAM_ILLEGAL")) {
			resultName = payState + "-参数非法";
		} else if (payState.toUpperCase().contains("successed")) {
			resultName = payState + "-支付成功";
		}
		return resultName;
	}

	/**
	 * 获取1688物流状态中英文信息
	 *
	 * @param logisticsState
	 */
	private String getAliLogisticsStateName(String logisticsState) {
		String resultName = "";
		if (logisticsState.toUpperCase().contains("WAITACCEPT")) {
			resultName = logisticsState + "-未受理";
		} else if (logisticsState.toUpperCase().contains("CANCEL")) {
			resultName = logisticsState + "-已撤销";
		} else if (logisticsState.toUpperCase().contains("ACCEPT")) {
			resultName = logisticsState + "-已受理";
		} else if (logisticsState.toUpperCase().contains("TRANSPORT")) {
			resultName = logisticsState + "-运输中";
		} else if (logisticsState.toUpperCase().contains("NOGET")) {
			resultName = logisticsState + "-揽件失败";
		} else if (logisticsState.toUpperCase().contains("SIGN")) {
			resultName = logisticsState + "-已签收";
		} else if (logisticsState.toUpperCase().contains("UNSIGN")) {
			resultName = logisticsState + "-签收异常";
		} else {
			resultName = logisticsState;
		}
		return resultName;
	}

	@Override
	public R get1688OrderLogisticsInfo(String orderNo) {
		try {
			if (StringUtils.isEmpty(orderNo)) {
				return R.error("参数orderNo不能为空！");
			}
			TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
			if (purchaseOrder == null) {
				return R.error("订单不存在");
			}
			Map<String, String> postParams = new HashMap<>();
			if (purchaseOrder != null) {
				String token = getCacheAccessToken();
				if (StringUtils.isEmpty(token)){
					logger.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
					return R.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。！");
				}
				long aop_timestamp = new Date().getTime();
				postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
				postParams.put("access_token", token);
				postParams.put("webSite", "1688");
				postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660419985562523597"
				String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsInfos.buyerView/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
				postParams.put("_aop_signature", aop_signature);
				String url = AppConstant.GET_ORDERLOGISTICSINFO_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
				JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
				if (jsonObject == null) {
					logger.error("调用获取1688采购订单物流信息接口返回不是一个JSON对象!");
					apiLogService.addApiLog("1688", "GET_ORDERLOGISTICSINFO_URL", "获取1688订单物流详细-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), JSON.toJSONString(jsonObject), 1, "定时获取物流信息失败get1688OrderLogisticsInfo");
					return R.error("调用获取1688采购订单物流信息接口返回不是一个JSON对象！");
				}
				boolean success = false;
				if (jsonObject.containsKey("success")) {
					success = jsonObject.getBoolean("success");
				}
				if (success == true) {
					String errorMsg = "";
					if (jsonObject.containsKey("errorMessage")) {
						errorMsg = jsonObject.getString("errorMessage");
					}
					if (!StringUtils.isEmpty(errorMsg)) {
						return R.error(errorMsg);
					} else {
						JSONArray logisticsResult = (JSONArray) jsonObject.get("result");
						if (logisticsResult != null && logisticsResult.size() > 0) {
							String aliLogisticsCompanyName = "";
							String alilLogisticsBillNo = "";
							String aliLogisticsCode = "";
							String aliLogisticsState = "";
							for (int i = 0; i < logisticsResult.size(); i++) {
								JSONObject logisticsItem = logisticsResult.getJSONObject(i);
								aliLogisticsState += getAliLogisticsStateName(logisticsItem.getString("status")) + ',';
								aliLogisticsCompanyName += logisticsItem.getString("logisticsCompanyName") + ',';
								alilLogisticsBillNo += logisticsItem.getString("logisticsBillNo") + ',';
								aliLogisticsCode += logisticsItem.getString("logisticsId");
							}
							if (aliLogisticsState.length() > 0) {
								aliLogisticsState = aliLogisticsState.substring(0, aliLogisticsState.length() - 1);
							}
							if (aliLogisticsCompanyName.length() > 0) {
								aliLogisticsCompanyName = aliLogisticsCompanyName.substring(0, aliLogisticsCompanyName.length() - 1);
							}
							if (alilLogisticsBillNo.length() > 0) {
								alilLogisticsBillNo = alilLogisticsBillNo.substring(0, alilLogisticsBillNo.length() - 1);
							}
							if (aliLogisticsCode.length() > 0) {
								aliLogisticsCode = aliLogisticsCode.substring(0, aliLogisticsCode.length() - 1);
							}
							TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
							tcgPurchaseOrder.setAliLogisticsCompanyName(aliLogisticsCompanyName);
							tcgPurchaseOrder.setAliLogisticsBillNo(alilLogisticsBillNo);
							tcgPurchaseOrder.setAliLogisticsCode(aliLogisticsCode);
							tcgPurchaseOrder.setAliLogisticsState(aliLogisticsState);
							tcgPurchaseOrder.setAliLogisticsPlace(aliLogisticsCompanyName);

							R r = get1688AliState(tcgPurchaseOrder.getAliOrderNumber());
							if (r.getCode() == 0){
								tcgPurchaseOrder.setAliState(r.getMsg());
							}
							tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);

							//新增线上采购入库单
							if (!alilLogisticsBillNo.equals("")){
								List<TcgPurchaseByOrderSon> tcgPurchaseOrderSonList = new TcgPurchaseByOrderSon().setPid(tcgPurchaseOrder.getId()).queryList();
								for (TcgPurchaseByOrderSon tcgPurchaseOrderSon : tcgPurchaseOrderSonList){
									tcgOfflinePurchaseInStorageService.addTcgOfflinePurchaseInStorage(tcgPurchaseOrder,tcgPurchaseOrderSon.getId(),
											alilLogisticsBillNo,aliLogisticsCompanyName,0
									, TcgOfflinePurchaseInStorageEnum.AssembledStatus.NOT_ASSEMBLY.value,null);
								}
							}
						}
					}
				} else {
					String errorMsg = "";
					if (jsonObject.containsKey("errorMessage")) {
						errorMsg = jsonObject.getString("errorMessage");
					}
					if (jsonObject.containsKey("error_message")) {
						errorMsg = jsonObject.getString("error_message");
					}
					return R.error("调用获取1688采购订单物流信息接口出错，具体错误为：" + errorMsg);
				}
			} else {
				logger.error("orderNo单号对应的订单不存在");
				return R.error("orderNo单号对应的订单不存在！");
			}
		}catch (Exception e) {
			//logger.error("ECP_API调用获取1688采购订单物流信息接口出错，错误信息为：" + e.getMessage());
			logger.error("ECP_API调用获取1688采购订单物流信息接口出错，错误信息为：" + e.getMessage(),e.getMessage(),e);
			return R.error("ECP_API调用获取1688采购订单物流信息接口出错，具体错误信息为：" + e.getMessage());
		}
		return R.ok("获取1688采购订单物流信息接口成功!");
	}

	/**
	 * 获取1688订单中的实际订单金额(
	 */
	@Override
	public BigDecimal get1688OrderAmountApi(String orderNo) {
		//1、先根据orderNo查询采购订单数据
		TcgPurchaseByOrder purchaseOrder = new TcgPurchaseByOrder().setBid(orderNo).queryFirst();
		if (purchaseOrder == null) {
			return null;
		}
		//此订单没有1688的订单编号
		if (StringUtils.isEmpty(purchaseOrder.getAliOrderNumber())) {
			return null;
		}
		BigDecimal orderAmountBig = null;
		Map<String, String> postParams = new HashMap<>();
		String token = getCacheAccessToken();
		long aop_timestamp = new Date().getTime();
		postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
		postParams.put("access_token", token);
		postParams.put("webSite", "1688");
		postParams.put("orderId", purchaseOrder.getAliOrderNumber());//"1660419985562523597"
		String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.get.buyerView/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
		postParams.put("_aop_signature", aop_signature);
		try {
			if (StringUtils.isEmpty(token)){
				logger.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				apiLogService.addApiLog("1688", "get1688OrderAmountApi", "1688订单信息-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				return null;
			}
			String url = AppConstant.GET_ORDERDETAIL_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
			JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
			if (jsonObject != null) {
				String success = "";
				if (jsonObject.containsKey("success")) {
					success = jsonObject.getString("success");
				}
				if (success.toLowerCase().equals("true")) {
					JSONObject orderResult = (JSONObject) jsonObject.get("result");
					if (orderResult != null) {
						JSONObject baseInfo = (JSONObject) orderResult.get("baseInfo");
						//订单状态信息
						if (baseInfo != null) {
							orderAmountBig = baseInfo.getBigDecimal("totalAmount");
						}
					}
				}
			}
		} catch (Exception ex) {
			//logger.error("ECP_API调用获取1688采购订单订单金额[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
			logger.error("ECP_API调用获取1688采购订单订单金额[" + orderNo + "]出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			apiLogService.addApiLog("1688", "get1688OrderAmountApi", "1688订单获取-orderNo：" + orderNo + "，postParams：" + JSON.toJSONString(postParams), "", 400, "ECP_API调用获取1688采购订单金额接口[" + orderNo + "]出错，错误信息为：" + ex.getMessage());
			return orderAmountBig;
		}
		return orderAmountBig;
	}

	@Override
	@Transactional(timeout = 300, propagation = Propagation.REQUIRES_NEW)
	public R get1688AliState(String aliOrderNumber) {
		try {
			if (StringUtils.isEmpty(aliOrderNumber)) {
				return R.error("订单标识不允许不能为空！");
			}
			Map<String, String> postParams = new HashMap<>();
			String token = getCacheAccessToken();
			long aop_timestamp = new Date().getTime();
			postParams.put("_aop_timestamp", String.valueOf(aop_timestamp));
			postParams.put("access_token", token);
			postParams.put("webSite", "1688");
			postParams.put("orderId", aliOrderNumber);//"1660419985562523597"
			String aop_signature = ApiHmacSHA1Utils.signatureWithParamsAndUrlPath("param2/1/com.alibaba.trade/alibaba.trade.get.buyerView/" + MyConfig.get1688AppKey(), postParams, MyConfig.get1688AppSecret());
			postParams.put("_aop_signature", aop_signature);
			if (StringUtils.isEmpty(token)){
				logger.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				apiLogService.addApiLog("1688", "Get1688OrderDetail", "1688订单信息-orderNo：" + aliOrderNumber + "，postParams：" + JSON.toJSONString(postParams), "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期，过期请通过”1688铺货“功能中“1688账户”点击进去进行重新授权。", 400, "token获取失败，请检查一下1688授权中“刷新授权日期”是否过期！");
				return R.error("token获取失败，请检查一下1688授权中“刷新授权日期”是否过期!");
			}
			String url = AppConstant.GET_ORDERDETAIL_URL.replace("YOUR_APPKEY", MyConfig.get1688AppKey());
			JSONObject jsonObject = ApiHttpUtils.sendHttpClientPost(url, postParams);
			if (jsonObject != null) {
				String success = "";
				if (jsonObject.containsKey("success")) {
					success = jsonObject.getString("success");
				}
				if (success.toLowerCase().equals("true")) {
					JSONObject orderResult = (JSONObject) jsonObject.get("result");
					if (orderResult != null) {
						logger.info("ECP_API调用获取1688采购订单接口成功!" + orderResult);
						JSONObject baseInfo = (JSONObject) orderResult.get("baseInfo");
						//订单状态信息
						if (baseInfo != null) {
							return R.ok(baseInfo.getString("status"));
						}
					}
				}
			}
			return R.ok("获取1688订单状态且修改采购完成单订单状态成功!");
		} catch (Exception ex) {
			logger.error("获取1688订单状态并修改采购完成单订单状态出错，错误信息为：" + ex.getMessage(),ex.getMessage(),ex);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("获取1688订单状态并修改采购完成单订单状态出错，具体错误信息为：" + ex.getMessage());
		}
	}
}
